package com.atguigu.gulimall.product.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.atguigu.common.constant.ProductConstant;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.Feign.SearchFeignClient;
import com.atguigu.gulimall.product.Feign.WareFeignClient;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.SpuInfoDao;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {
    @Autowired
    SkuInfoService skuInfoService;
    @Autowired
    private BrandServiceImpl brandService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private ProductAttrValueService productAttrValueService;
    @Autowired
    private AttrService attrService;
    @Autowired
    private WareFeignClient wareFeignClient;
    @Autowired
    private SearchFeignClient searchFeignClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void up(Long spuId) {
        //1.查出当前spuid对应的所有sku信息，品牌的名字
        List<SkuInfoEntity> skuInfoEntities = skuInfoService.getSkuInfoBySpuId(spuId);
        //4.查询当前所有sku的可以被检索的规格属性
        List<ProductAttrValueEntity> productAttrValueEntities = productAttrValueService.list(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId));
        List<SkuEsModel.Attr> valueEntityList = productAttrValueEntities.stream().filter(e -> {
                    List<AttrEntity> list = attrService.list(new QueryWrapper<AttrEntity>().eq("attr_id", e.getAttrId()).eq("search_type", 1));
                    for (AttrEntity attrEntity : list) {
                        if (attrEntity.getAttrId().equals(e.getAttrId())) {
                            return true;
                        }
                    }
                    return false;
                }
        ).map(e -> {
            SkuEsModel.Attr attr = new SkuEsModel.Attr();
            attr.setAttrId(e.getAttrId());
            attr.setAttrName(e.getAttrName());
            attr.setAttrValue(e.getAttrValue());
            return attr;
        }).collect(Collectors.toList());

        List<Long> skuIds = skuInfoEntities.stream().map(e -> e.getSkuId()).collect(Collectors.toList());
        Map<Long, Boolean> map = null;
        try {
            //远程查库存 3 .hasStock
            Object data = wareFeignClient.getSkuHasStock(skuIds).get("data");
            //转换json，强转用stream会报转换异常
            JSONArray jsonArray = JSONUtil.parseArray(data);
            List<SkuHasStockVo> hasStockVoList1 = JSONUtil.toList(jsonArray, SkuHasStockVo.class);
            if (!CollUtil.isEmpty(hasStockVoList1)) {
                map = hasStockVoList1.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


        Map<Long, Boolean> finalMap = map;
        List<SkuEsModel> upProducts = skuInfoEntities.stream().map(e -> {
            //组装需要的数据
            SkuEsModel skuEsModel = new SkuEsModel();
            BeanUtil.copyProperties(e, skuEsModel);
            skuEsModel.setSkuPrice(e.getPrice());
            skuEsModel.setSkuImg(e.getSkuDefaultImg());
            // 2. 热度评分，0
            skuEsModel.setHotScore(0L);
            //设置品牌，分类名
            BrandEntity brandEntity = brandService.getById(e.getBrandId());
            skuEsModel.setBrandName(brandEntity.getName());
            skuEsModel.setBrandImg(brandEntity.getLogo());
            CategoryEntity categoryEntity = categoryService.getById(e.getCatalogId());
            skuEsModel.setCatalogName(categoryEntity.getName());
            //设置属性
            skuEsModel.setAttrs(valueEntityList);
            //设置是否有库存
            if (finalMap == null) {
                skuEsModel.setHasStock(true);
            } else {
                skuEsModel.setHasStock(finalMap.get(e.getSkuId())==null?false:true);
            }
            return skuEsModel;
        }).collect(Collectors.toList());

        //TODO，5，远程调用es的保存方法
        R r = searchFeignClient.productStatusUp(upProducts);
        if(r.getCode()==0){
            baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        }else{
            //远程失败
            // todo 重试机制
        }
    }

    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
        SkuInfoEntity skuInfoEntity = skuInfoService.getById(skuId);
        SpuInfoEntity spuInfoEntity = baseMapper.selectById(skuInfoEntity.getSpuId());
        return spuInfoEntity;
    }

}